package top.jacktgq.itheima.netty.protocol_design.groupchat.rpc;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import top.jacktgq.itheima.netty.protocol_design.groupchat.protocol.MessageCodecSharable;
import top.jacktgq.itheima.netty.protocol_design.groupchat.protocol.ProtocolFrameDecoder;

/**
 * @Author CandyWall
 * @Date 2021/3/24--13:38
 * @Description 聊天服务器
 */
@Slf4j
public class RpcServer {
    public static void main(String[] args) {
        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable messageCodec = new MessageCodecSharable();
        RpcRequestMessageHandler rpcRequestMessageHandler = new RpcRequestMessageHandler();

        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(2);
        ChannelFuture channelFuture = new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new ProtocolFrameDecoder())
                                .addLast(loggingHandler)
                                .addLast(messageCodec)
                                .addLast(rpcRequestMessageHandler);
                    }
                })
                .bind(8080);
        // 监听服务器启动事件
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.debug("RPC服务器启动成功...监听在8080端口");

                // 监听服务器ServerSocketChannel关闭事件，从而停止服务器端的事件循环组中的事件循环
                channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        bossGroup.shutdownGracefully();
                        workerGroup.shutdownGracefully();
                    }
                });
            }
        });
    }
}
